//
//  SoapHeader.m
//  wsdlWebService
//
//  Created by wulanzhou on 2017/10/11.
//  Copyright © 2017年 wulanzhou. All rights reserved.
//

#import "SoapHeader.h"


@interface SoapHeader (){
    
    NSMutableDictionary *postDataDic_;
}
@property (nonatomic,readonly) NSMutableDictionary *postDataDic;
@end


@implementation SoapHeader

@synthesize postDataDic=postDataDic_;

- (id)init {
    
    if (self=[super init]) {
        
        postDataDic_=[NSMutableDictionary dictionaryWithCapacity:0];
    }
    return self;
}


/**
 *  基于参数(data=)封装
 *
 *  @param firstObject 可变参数 key与value组成
 */
-(void)paramWithObjectsAndKeys:(NSString*)firstObject, ... NS_REQUIRES_NIL_TERMINATION{
    NSMutableArray *values=[NSMutableArray arrayWithCapacity:0];
    NSMutableArray *keys=[NSMutableArray arrayWithCapacity:0];
    NSInteger index=0;
    va_list args;
    va_start(args,firstObject);
    if(firstObject)
    {
        [values addObject:firstObject];
        index++;
        NSString *otherString;
        while((otherString=va_arg(args,NSString*)))
        {
            if (index%2==0){
                [values addObject:otherString];
            }else{
                //依次取得所有参数
                [keys addObject:otherString];
            }
            index++;
        }
    }
    va_end(args);
    
    NSAssert([values count]==[keys count], @"paramWithObjectsAndKeys方法设置的key与value不匹配!");
    
    if([keys count]>0&&[values count]>0)
    {
        for(NSInteger i=0;i<[values count];i++)
        {
            [self setParamValue:[values objectAtIndex:i] name:[keys objectAtIndex:i]];
        }
    }
}

/**
 soap header字值串
 
 @return 返回soap header字值串 如：<soapenv:Header/>
 */
- (NSString *)soapHeaderString{

    __block NSMutableString *headers = [NSMutableString stringWithString:@""];
    if ([postDataDic_ count]>0) {
        
        [postDataDic_ enumerateKeysAndObjectsUsingBlock:^(NSString  *key, id  _Nonnull obj, BOOL * _Nonnull stop) {
            [headers appendFormat:@"<%@>%@</%@>",key,obj,key];
        }];
        
        
    }
    
    if([headers length] == 0){
    
        return @"<soapenv:Header />";
    }
    
    return [NSString stringWithFormat:@"<soapenv:Header>%@</soapenv:Header>",headers];
    
}

#pragma  mark -私有方法

/**
 *  基于参数(data=)封装
 *
 *  @param value 参数值
 *  @param key   参数名
 */
- (void)setParamValue:(NSString*)value name:(NSString*)key{
    [postDataDic_ setValue:value forKey:key];
}


@end
